package com.example.common.config;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

@Configuration
public class JsonConfig {
	@Bean
	public LocalDateTimeDeserializer localDateTimeDeserializer(JacksonProperties jacksonProperties) {
		return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat()));
	}

	@Bean
	public LocalDateTimeSerializer localDateTimeSerializer(JacksonProperties jacksonProperties) {
		return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat()));
	}

	@Bean
	@Primary
	public SimpleModule localDateTimeSimpleModule(LocalDateTimeDeserializer localDateTimeDeserializer,
			LocalDateTimeSerializer localDateTimeSerializer) {
		SimpleModule module = new SimpleModule();

		module.addSerializer(LocalDateTime.class, localDateTimeSerializer);
		module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);

		return module;
	}

	@Bean
	@Primary
	public ObjectMapper objectMapper(SimpleModule localDateTimeSimpleModule, JacksonProperties jacksonProperties) {
		var objectMapper = new ObjectMapper();

		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

		objectMapper.registerModule(localDateTimeSimpleModule);
		objectMapper.setDateFormat(new SimpleDateFormat(jacksonProperties.getDateFormat()));

		return objectMapper;
	}
}
